﻿using System;
using MediatR;
using System.Collections.Generic;
using Casamiel.Domain;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.MWeb;
using System.Threading;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.Extensions.Options;
using Casamiel.Common;
using Newtonsoft.Json;
using System.Linq;

using Casamiel.Domain.Request;
using Newtonsoft.Json.Linq;

namespace Casamiel.Application.Commands
{
    /// <summary>
    /// Get product by identifier store identifier command handler.
    /// </summary>
    public sealed class GetProductByIdStoreIdCommandHandler : BaseCommandHandler, IRequestHandler<GetProductByIdStoreIdCommand, BaseResult<GoodsProductBaseRsp>>
    {
        private readonly IMbrStoreRepository _mbrStoreRepository;
        /// <summary>
        /// Initializes a new instance of the
        /// <see cref="T:Casamiel.Application.Commands.GetProductByIdStoreIdCommandHandler"/> class.
        /// </summary>
        /// <param name="mbrStoreRepository">Mbr store repository.</param>
        /// <param name="netICService">Net ICS ervice.</param>
        /// <param name="httpClientFactory">Http client factory.</param>
        /// <param name="settings">Settings.</param>
        public GetProductByIdStoreIdCommandHandler(IMbrStoreRepository mbrStoreRepository, INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)
        {
            _mbrStoreRepository = mbrStoreRepository;
        }
        /// <summary>
        /// Handle the specified request and cancellationToken.
        /// </summary>
        /// <returns>The handle.</returns>
        /// <param name="request">Request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<BaseResult<GoodsProductBaseRsp>> Handle(GetProductByIdStoreIdCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var storeinfo = await _mbrStoreRepository.GetByStoreIdAsync<ICasaMielSession>(request.StoreId).ConfigureAwait(false);
            if (storeinfo == null)
            {
                return new BaseResult<GoodsProductBaseRsp>(null, 999, "storeid 有误");
            }
            var url = "CakeMall/v3/Goods/GetById";//根据商品Id和门店Id获取商品信息
            var rsp = await PostThirdApiAsync<GoodsProductBaseRsp>(url, JsonConvert.SerializeObject(new { storeId = request.StoreId, productId = request.ProductId })).ConfigureAwait(false);
            //var rsp = JsonConvert.DeserializeObject<JObject>(result);
            if (rsp.Code > 0)
            {
                return rsp;
            }
            var GoodsBase = rsp.Content;// JsonConvert.DeserializeObject<Goods_ProductBaseRsp>(rsp["data"].ToString());
            if (rsp.Content != null)
            {
                var req = new ProductStockQueryReq { datasource = request.DataSource, shopid = storeinfo.RelationId, product = new List<Domain.Request.ProductStockReq>() };
                if (rsp.Content.GoodsList.Count > 0)
                {
                    foreach (var item in rsp.Content.GoodsList)
                    {
                        req.product.Add(new ProductStockReq { pid = $"{item.RelationId }" });
                    }
                    //var zmodel = await NetICService.Productstockquery(req).ConfigureAwait(false);
                    //if (zmodel != null)
                    //{
                    //    var _count = GoodsBase.GoodsList.Count;
                    //    for (int i = 0; i < _count; i++)
                    //    {
                    //        var t = zmodel.product.Find(a => a.pid == $"{GoodsBase.GoodsList[i].RelationId}");
                    //        if (t != null && t.icprice > 0)
                    //        {
                    //            GoodsBase.GoodsList[i].Price = t.originprice;
                    //            GoodsBase.GoodsList[i].CostPrice = t.icprice;
                    //            if (storeinfo.IsLimitStock == 1)
                    //            {
                    //                GoodsBase.GoodsList[i].StockQuentity = 100;
                    //            }
                    //            else
                    //            {
                    //                //if (DateTime.Now > DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30")))
                    //                //{
                    //                //    //if (t.count > 0)
                    //                //    //{
                    //                //    //    int a = await _storeService.GetGoodsQuantityByPidAsync<ICasaMielSession>(item.RelationId, DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd 19:30")));
                    //                //    //    item.StockQuentity = t.count - a;
                    //                //    //}
                    //                //    //else
                    //                //    //{
                    //                //    item.StockQuentity = t.count;
                    //                //    //}
                    //                //}
                    //                //else
                    //                //{
                    //                GoodsBase.GoodsList[i].StockQuentity = t.count;
                    //                //}

                    //            }
                    //        }
                    //    }

                    //}
                }

            }
            return rsp;
            //return new BaseResult<Goods_ProductBaseRsp>(GoodsBase, 0, "");
        }
    }
}
